package com.ptszyxx.popose.module.main.gift.vm;

import android.app.Application;
import androidx.annotation.NonNull;
import com.google.gson.Gson;
import com.ptszyxx.popose.common.utils.YActivityUtil;
import com.ysg.enums.ChatCallEnum;
import com.ysg.http.callback.OnErrorResult;
import com.ysg.utils.YUserUtil;
import com.tencent.imsdk.v2.V2TIMManager;
import com.tencent.imsdk.v2.V2TIMMessage;
import com.tencent.imsdk.v2.V2TIMValueCallback;
import com.tencent.qcloud.tuikit.tuichat.zhiyu.bean.SendGifts1v1Bean;
import com.tencent.qcloud.tuikit.tuichat.zhiyu.callback.CustomMessageCallback;
import com.ysg.base.BaseViewModel;
import com.ysg.binding.command.BindingCommand;
import com.ysg.bus.event.SingleLiveEvent;
import com.ysg.callback.StringCallback;
import com.ysg.http.BaseResponse;
import com.ysg.http.HttpUtils;
import com.ysg.http.callback.OnSuccessResult;
import com.ysg.http.data.CommonRepository;
import com.ysg.http.data.entity.im.ChatBlackEntity;
import com.ysg.http.data.entity.im.ChatDiamondEnoughEntity;
import com.ysg.http.data.entity.im.ChatVideoMatchEntity;
import com.ysg.utils.YSPUtils;
import com.ysg.utils.YStringUtil;
import com.ysg.utils.YToastUtil;
import com.ysg.widget.dialog.entity.GiftListResult;
import com.ysg.widget.dialog.entity.GiftNumResult;
import java.util.HashMap;
import java.util.Map;

/**
 * 礼物和拨打电话
 */
public class GiftAndCallVM extends BaseViewModel<CommonRepository> {
    public GiftListResult giftListEntity;
    public GiftNumResult giftNumResult;
    //拨打电话
    public ChatBlackEntity blackEntity;
    public boolean intimacyEnoughFlag;//亲密度是否足够标记（针对男生）
    private String txUserId;

    public GiftAndCallVM(@NonNull Application application, CommonRepository model) {
        super(application, model);
    }

    //TODO 2.ui通知处理=====================
    public UIChangeObservable baseUC = new UIChangeObservable();
    public class UIChangeObservable {
        //礼物
        public SingleLiveEvent onGiftDialogEvent = new SingleLiveEvent<>();
        //拨打电话
        public SingleLiveEvent onCallDialogEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onCallPriceEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onIntimacyEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onNoDiamondEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onNoDiamondGiftEvent = new SingleLiveEvent<>();
        public SingleLiveEvent onNoDiamondCallEvent = new SingleLiveEvent<>();
    }

    public BindingCommand onGiftCommand = new BindingCommand(()-> onGiftClick());


    //==================================================1.礼物：start============================================================================
    /**
     * 处理点击礼物按钮
     */
    public void onGiftClick(){
        if (giftListEntity != null && giftNumResult != null){
            baseUC.onGiftDialogEvent.call();
        }else{
            requestGift();
        }
    }

    /**
     * 礼物列表
     */
    private void requestGift(){
        Map<String, String> map = new HashMap<>();
        HttpUtils.getInstance()
                .data(model.giftList(map), this,
                        new OnSuccessResult<GiftListResult>() {
                            @Override
                            public void onSuccessResult(BaseResponse<GiftListResult> response) {
                                giftListEntity = response.getData();
                                requestGiftNum();
                            }
                        });
    }
    /**
     * 礼物数量
     */
    private void requestGiftNum(){
        Map<String, String> map = new HashMap<>();
        HttpUtils.getInstance()
                .data(model.giftNum(map), this,
                        new OnSuccessResult<GiftNumResult>() {
                            @Override
                            public void onSuccessResult(BaseResponse<GiftNumResult> response) {
                                giftNumResult = response.getData();
                                baseUC.onGiftDialogEvent.call();
                            }
                        });
    }

    /**
     * 发送礼物
     */
    public void requestSendGift(GiftListResult.GiftBean giftBean, GiftNumResult.Data giftNumEntity, String txUserId, CustomMessageCallback messageCallback,  StringCallback callback){
        Map<String, String> map = new HashMap<>();
        map.put("userid", txUserId);
        map.put("giftid", giftBean.getId() + "");
        map.put("giftnumid", giftNumEntity.getId() + "");
        HttpUtils.getInstance()
                .data(model.sendGift(map), this,
                        new OnSuccessResult() {
                            @Override
                            public void onSuccessResult(BaseResponse response) {
                                try {
                                    GiftListResult giftEntity = giftListEntity;
                                    double d = Double.valueOf(giftEntity.getDiamonds()) - (giftBean.getGoldmoney() * giftNumEntity.getNum());
                                    giftEntity.setDiamonds(d + "");
                                    sendMessageGift(giftBean, giftNumEntity, txUserId, messageCallback);

                                    //播放礼物动画
                                    if (callback != null) {
                                        callback.onResult(giftBean.getSvgaaddress());
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }, new OnErrorResult() {
                            @Override
                            public void onErrorResult(int code, String msg) {
                                baseUC.onNoDiamondGiftEvent.call();
                            }
                        });
    }

    /**
     * 发送礼物后，发一条自定义信息
     */
    public void sendMessageGift(GiftListResult.GiftBean giftBean, GiftNumResult.Data giftNumEntity, String txUserId, CustomMessageCallback messageCallback){
        if (giftBean != null && giftNumEntity != null){
            SendGifts1v1Bean sendGifts1v1Bean = new SendGifts1v1Bean();
            sendGifts1v1Bean.setImg(giftBean.getPicture() + "");
            sendGifts1v1Bean.setType("@@@@@***");
            sendGifts1v1Bean.setGiftsName(giftBean.getGiftname() + "");
            sendGifts1v1Bean.setText("");
            sendGifts1v1Bean.setGiftsNum(giftNumEntity.getNum() + "");
            sendGifts1v1Bean.setUuid("");
            sendGifts1v1Bean.setGiftsId(giftBean.getId() + "");
            sendGifts1v1Bean.setGiftsPrice(giftBean.getGoldmoney() + "");
            sendGifts1v1Bean.setSvgaUrl(giftBean.getSvgaaddress() + "");

            if (messageCallback != null){
                messageCallback.onSendGift(sendGifts1v1Bean);
            }else{
                String dataText = new Gson().toJson(sendGifts1v1Bean);
                V2TIMManager.getInstance().sendC2CCustomMessage(dataText.getBytes(), txUserId, new V2TIMValueCallback<V2TIMMessage>() {
                    @Override
                    public void onSuccess(V2TIMMessage message) {
                    }
                    @Override
                    public void onError(int code, String desc) {
                    }
                });
            }
        }
    }

    /**
     * 发送常用语
     */
    public void sendMessageExpression(String text, String txUserId){
        V2TIMManager.getInstance().sendC2CTextMessage(text, txUserId, new V2TIMValueCallback<V2TIMMessage>() {
            @Override
            public void onSuccess(V2TIMMessage message) {
            }
            @Override
            public void onError(int code, String desc) {
            }
        });
    }
    //==================================================1.礼物：end============================================================================



    //==================================================2.拨打电话：start============================================================================


    /**
     * 点击“打电话”按钮
     */
    public void onCallClick(String txUserId, ChatCallEnum callEnum){
        this.txUserId = txUserId;

        if (callEnum == null){
            //聊天
            if (YUserUtil.isGirl() || intimacyEnoughFlag){
                baseUC.onCallDialogEvent.call();
            }else{
                boolean showPriced = YSPUtils.getInstance().getShowVideoAudioPrice(txUserId);
                if (showPriced){
                    requestIsBlack(ChatCallEnum.CALL, txUserId);
                }else{
                    baseUC.onCallPriceEvent.call();
                }
            }
        }else{
            //用户信息
            if (YUserUtil.isGirl() || intimacyEnoughFlag){
                requestVideoAudioIsEnough(callEnum);
            }else{
                requestIsBlack(callEnum, txUserId);
            }
        }

    }


    /**
     * 1.是否被拉黑
     * 2.是否免费
     * 3.亲密度
     */
    public void requestIsBlack(ChatCallEnum callEnum, String txUserId){
        Map<String, String> map = new HashMap<>();
        map.put("tengxuncode", txUserId);
        HttpUtils.getInstance()
                .data(model.isBlack(map), this, new OnSuccessResult<ChatBlackEntity>() {
                    @Override
                    public void onSuccessResult(BaseResponse<ChatBlackEntity> response) {
                        blackEntity = response.getData();
                        if (callEnum != null){
                            onIntimacy(callEnum);
                        }
                    }
                });
    }

    /**
     * 处理亲密度
     * 如果亲密度足够
     * a.语音价格：直接拨打语音通话
     * b。视频价格：直接拨打视频通话
     * c.弹窗选择：语音通话还是视频通话
     *
     * 如果亲密度不够：弹窗送礼物
     */
    private void onIntimacy(ChatCallEnum callEnum){
        try {
            if (blackEntity == null){
                return;
            }
            if (YStringUtil.isNotEmpty(blackEntity.getIntimacy()) && YStringUtil.isNotEmpty(blackEntity.getIntimacyvoice())){
                if (Double.valueOf(blackEntity.getIntimacy()) >= Double.valueOf(blackEntity.getIntimacyvoice())){
                    intimacyEnoughFlag = true;
                    switch (callEnum){
                        case AUDIO:
                            requestVideoAudioIsEnough(callEnum);
                            break;
                        case CALL:
                            baseUC.onCallDialogEvent.call();
                            break;
                    }
                }else{
                    baseUC.onIntimacyEvent.setValue(blackEntity.getIntimacyvoice());
                }
            }
        }catch (Exception e){
            e.printStackTrace();
            YToastUtil.showShort("亲密度："+blackEntity.getIntimacy() + "解锁亲密度："+blackEntity.getIntimacyvoice());
        }
    }

    /**
     * 通话的钻石是否足够-----------2
     */
    public void requestVideoAudioIsEnough(ChatCallEnum callEnum){
        if (YUserUtil.isGirl() || YStringUtil.eq(1, blackEntity.getFree())){
            requestVideoMatch(callEnum);
        }else{
            Map<String, String> map = new HashMap<>();
            map.put("tengxuncode", txUserId);
            map.put("type", ChatCallEnum.AUDIO == callEnum? "1": "2");
            HttpUtils.getInstance()
                    .data(model.videoAudioIsEnough(map), this, new OnSuccessResult<ChatDiamondEnoughEntity>() {
                        @Override
                        public void onSuccessResult(BaseResponse<ChatDiamondEnoughEntity> response) {
                            if ((ChatCallEnum.AUDIO == callEnum && YStringUtil.eq(0, response.getData().getIsEnoughVoice()))
                                    || (ChatCallEnum.VIDEO == callEnum && YStringUtil.eq(0, response.getData().getIsEnoughVideo()))
                            ){
                                YToastUtil.showShort("您的钻石不足,请充值");
                                baseUC.onNoDiamondCallEvent.call();
                                return;
                            }
                            requestVideoMatch(callEnum);
                        }
                    });
        }
    }
    /**
     * 判断用户是否在视频匹配---------3
     */
    public void requestVideoMatch(ChatCallEnum callEnum){
        Map<String, String> map = new HashMap<>();
        map.put("txCode", txUserId);
        HttpUtils.getInstance()
                .data(model.videoMatch(map), this, new OnSuccessResult<ChatVideoMatchEntity>() {
                    @Override
                    public void onSuccessResult(BaseResponse<ChatVideoMatchEntity> response) {
                        if (YStringUtil.eq(1, response.getData().getJieguo())){
                            YActivityUtil.getInstance().jumpChatCall(txUserId, callEnum);
                        }else {
                            YToastUtil.showShort("对方忙！");
                        }
                    }
                });
    }

    //==================================================2.拨打电话：end============================================================================
}
